//
//  YJSDelegate.swift
//  YFree
//
//  Created by YMac on 2018/11/23.
//  Copyright © 2018 yangzhe. All rights reserved.
//
import SafariServices

open class YJSDelegate: NSObject,WKNavigationDelegate {
    open var vc:YUIViewController!
    open var webView:YWebView!
    open var progress:WebviewProgressLine?
    open var canShowProgress = false
    
    open func getJsObjName() -> String { return "yPhone" }
    
    public init(canShowProgress:Bool = false) {
        self.canShowProgress = canShowProgress
    }
    
    open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.webView = webView as! YWebView
        self.vc = webView.viewContainingController() as? YUIViewController
        if canShowProgress{
            self.progress = WebviewProgressLine(frame: CGRect(x: 0, y: webView.frame.origin.y, width: vc.yScreenWidth, height: 3))
            progress!.lineColor = YConfig.themeColor
            webView.superview?.addSubview(progress!)
            self.progress?.startLoadingAnimation()
        }
        yWebViewDidStartLoad()
    }
    
    open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if canShowProgress {
            progress?.endLoadingAnimation()
            progress?.removeFromSuperview()
            progress = nil
        }
        yWebViewDidFinishLoad()
    }
    
    open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        if canShowProgress {
            progress?.endLoadingAnimation()
            progress?.removeFromSuperview()
            progress = nil
        }
        yDidFailLoadWithError()
    }
    
    open func yWebViewDidStartLoad() {}
    open func yWebViewDidFinishLoad() {}
    open func yDidFailLoadWithError() {}
    
    @objc open func getDevice(_ param: Any) -> String { return YConfig.device }
    
    @objc open func getAppName(_ param: Any) -> String {
        return YAppUtils.getAppName()
    }
    
    @objc open func getVersion(_ param: Any) -> String {
        return YAppUtils.getAppVersionCode()
    }
    
    @objc open func getIP(_ param: Any) -> String {
        return YConfig.IP
    }
    
    @objc open func getDebug(_ param: Any) -> String {
        return YConfig.DEBUG ? "1" : "0"
    }
    
    @objc open func getHttpHeader(_ param: Any) -> String {
        return "{}"
    }
    
    @objc open func getUserEntity(_ param: Any) -> String {
        return ""
    }
    
    @objc open func closeKeyBoard(_ param: Any) {
        self.vc.yRunOnUIThread {
            self.vc.yCloseKeyBoard()
        }
    }
    
    @objc open func openQQ(_ qq: Any) {
        YQQUtils.openQQ(vc: self.vc, "\(qq)")
    }
    
    @objc open func goBack(_ param: Any) {
        self.vc.yRunOnUIThread {
            self.webView.goBack()
        }
    }
    
    @objc open func close(_ param: Any) {
        self.vc.yRunOnUIThread {
            self.vc.yPopVC()
        }
    }
    
    @objc open func close2(_ param: Any) {
        self.vc.yRunOnUIThread {
            self.vc.yDismissVC()
        }
    }
    
    @objc open func openBrowser(_ url: Any) {
        UIApplication.shared.openURL(URL(string: "\(url)")!)
    }
    
    @objc open func openBrowser2(_ url: Any){
        let webVC = SFSafariViewController(url: URL(string: "\(url)")!)
        if #available(iOS 10.0, *) {
            webVC.preferredBarTintColor = YConfig.navigationBarTintColor
        }
        self.vc.present(webVC, animated: true, completion: nil)
    }
    
    @objc open func log(_ msg: Any) {
        self.vc.yPrint("\(msg)")
    }
    
    @objc open func toast(_ msg: Any) {
        self.vc.yToast("\(msg)".replacingOccurrences(of: "<br/>", with: "\n"))
    }
    
    @objc open func showProgress(_ param: Any) {
        self.vc.yShowLoadingProgress()
    }
    
    @objc open func dismissProgress(_ param: Any) {
        self.vc.yDismissLoadingProgress()
    }
    
    @objc open func copy(_ content: Any){
        UIPasteboard.general.string = "\(content)"
    }
    
    @objc open func post(_ param: Any, handler: @escaping JSCallback){
        let dic = param as! NSDictionary
        let ip = "\(dic["IP"]!)"
        let jkid = "\(dic["jkid"]!)"
        let params = dic["params"] as! NSDictionary
        let kv = YJsonKV()
        params.forEach { (map) in  _ = kv.put("\(map.key)", "\(map.value)") }
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self.vc, delegateQueue: OperationQueue.main)
        session.dataTask(with: YAppDelegate.getRequestByRequest(viewController: self.vc,ip:ip,jkid: jkid,inputJsonKV: kv,httpMethod: "POST")) { (resultData, response , error) in
            let result = NSMutableDictionary()
            if error != nil {
                result["code"] = 0
                result["message"] = YConfig.DEBUG ? "网络请求异常！！！\(error!.localizedDescription)" : "网络请求错误，请重试"
            } else {
                if resultData != nil {
                    result["code"] = 1
                    result["result"] = String(data: resultData!, encoding: .utf8)
                } else {
                    result["code"] = 0
                    result["message"] = YConfig.DEBUG ? "网络请求响应为空" : "网络请求错误，请重试"
                }
            }
            handler(String(data: try! JSONSerialization.data(withJSONObject: result, options: .prettyPrinted), encoding: .utf8), true)
        }.resume()
    }
    
    //self
    open func yPresentVC(storyBoardName: String, storyBoardIdentifier: String, yBundle: [String : Any]? = nil) {
        self.vc.yRunOnUIThread { self.vc.yPresentVC(storyBoardName: storyBoardName, storyBoardIdentifier: storyBoardIdentifier, yBundle: yBundle) }
    }
    
    open func yPushVC(storyBoardName: String, storyBoardIdentifier: String, yBundle: [String : Any]? = nil) {
        self.vc.yRunOnUIThread { self.vc.yPushVC(storyBoardName: storyBoardName, storyBoardIdentifier: storyBoardIdentifier, yBundle: yBundle) }
    }
    
    open func yPresentVC(viewController: YUIViewController, storyBoardName: String, storyBoardIdentifier: String, yBundle: [String : Any]? = nil) {
        viewController.yRunOnUIThread { viewController.yPresentVC(storyBoardName: storyBoardName, storyBoardIdentifier: storyBoardIdentifier, yBundle: yBundle) }
    }
    
    open func yPushVC(viewController: YUIViewController, storyBoardName: String, storyBoardIdentifier: String, yBundle: [String : Any]? = nil) {
        viewController.yRunOnUIThread { viewController.yPushVC(storyBoardName: storyBoardName, storyBoardIdentifier: storyBoardIdentifier, yBundle: yBundle) }
    }
    
    open func yDismissVC(_ completion: (() -> Void)? = nil) {
        self.vc.yRunOnUIThread { self.vc.yDismissVC(completion) }
    }
    
    open func yPopVC(){
        self.vc.yRunOnUIThread { self.vc.yPopVC() }
    }
    
    open func yPopVCWithResult(responseCode: Int, data: Any?){
        self.vc.yRunOnUIThread { self.vc.yPopVCWithResult(responseCode: responseCode, data: data) }
    }
    
    open func yPopToTargetVC(viewController:YUIViewController){
        self.vc.yRunOnUIThread { self.vc.yPopToTargetVC(viewController: viewController) }
    }
    
    open func yPopToRootVC(){
        self.vc.yRunOnUIThread { self.vc.yPopToRootVC() }
    }
    
    open func yEvaluateScript(_ script:String){
        switch self.vc {
        case is YWebUIViewController:
            (self.vc as! YWebUIViewController).yEvaluateScript(script)
//        case is YWebUIViewController2:
//            (self.vc as! YWebUIViewController2).yEvaluateScript(script)
        default: break
        }
    }
}
